const $api = require('../../utils/request.js').Api;
var app = getApp();
Page({
  data: {
    currentTab: 0,
    sleft: "", //横向滚动条位置
    list: [],
    goodlist: [],
    curId: '',
  },
  // 获取商品分类
  initGoodType() {
    $api.getGoodsTypes().then((res) => {
      var newArr = res.map(function (item) {
        return {
          id: item.id,
          typeName: item.typeName,
        }
      })
      this.setData({
        list: newArr,
      })
      if (this.data.curId != '' || this.data.curId != undefined || this.data.curId != 'undefined') {
        console.log('2222222222')
        var id = this.data.curId
        var index = newArr.findIndex(item => item.id == id);
        this.setData({
          currentTab: index
        })
        this.initGoodList(id)
      } else {
        console.log('11111111')
        this.setData({
          currentTab: 0
        })
        const id = res[0].id
        this.initGoodList(id);
      }
    })
  },
  // 获取商品列表
  initGoodList(id) {
    $api.getGoodsList(id).then((res) => {
      var newArr = res.content.map(function (item) {
        return {
          id: item.id,
          price: item.price,
          title: item.goodsName,
          pic: JSON.parse(item.textMap.pics$DICT_TEXT_)[0].absolutePath,
          contacts: item.contacts
        }
      })
      this.setData({
        goodlist: newArr
      })
    })
  },
  // 跳转到商品详情
  skipTravelDetails: function (e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../../pages/productdetail/productdetail?id=${id}`,
    })
  },
  onLoad: function (options) {
    this.setData({
      curId: options.id,
    });
    this.initGoodType();
  },
  handleTabChange(e) {
    let {
      current
    } = e.target.dataset;
    console.log(current)
    if (this.data.currentTab == current || current === undefined) return;
    this.setData({
      currentTab: current,
    });
    const num = e.target.dataset.current
    this.initGoodList(this.data.list[num].id);
  },
  handleSwiperChange(e) {
    this.setData({
      currentTab: e.detail.current,
    });
    this.getScrollLeft();
    const num = e.detail.current
    this.initGoodList(this.data.list[num].id);
  },
  getScrollLeft() {
    const query = wx.createSelectorQuery();
    query.selectAll(".item").boundingClientRect();
    query.exec((res) => {
      let num = 0;
      for (let i = 0; i < this.data.currentTab; i++) {
        num += res[0][i].width;
      }
      this.setData({
        sleft: Math.ceil(num),
      });
    });
  },
})